import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
import math

import numpy as np


class BatchNorm2d(nn.Module):
    def __init__(self, in_planes, bn_branch=7):
        super(BatchNorm2d, self).__init__()
        self.bn_tree = nn.ModuleList([nn.BatchNorm2d(in_planes) for i in range(bn_branch)])
        self.rbi = True
    
    def forward(self, x):
        x,bn_r = x
        if self.rbi:
            y = self.bn_tree[bn_r](x)
        else:
            y = self.bn_tree[0](x)
        return y

class BasicBlock_RBN(nn.Module):
    def __init__(self, in_planes, out_planes, stride, bn_branch, dropRate=0.0):
        super(BasicBlock_RBN, self).__init__()
        self.bn1 = BatchNorm2d(in_planes, bn_branch)
        self.relu1 = nn.ReLU(inplace=True)
        self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                               padding=1, bias=False)
        self.bn2 = BatchNorm2d(out_planes, bn_branch)
        self.relu2 = nn.ReLU(inplace=True)
        self.conv2 = nn.Conv2d(out_planes, out_planes, kernel_size=3, stride=1,
                               padding=1, bias=False)
        self.droprate = dropRate
        self.equalInOut = (in_planes == out_planes)
        self.convShortcut = (not self.equalInOut) and nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride,
                                                                padding=0, bias=False) or None

    def forward(self, x):
        x, bn_pair = x
        if not self.equalInOut:
            x = self.relu1(self.bn1((x,bn_pair[0])))
        else:
            out = self.relu1(self.bn1((x,bn_pair[0])))
        out = self.relu2(self.bn2((self.conv1(out if self.equalInOut else x),bn_pair[1])))
        if self.droprate > 0:
            out = F.dropout(out, p=self.droprate, training=self.training)
        out = self.conv2(out)
        return torch.add(x if self.equalInOut else self.convShortcut(x), out)


class NetworkBlock_RBN(nn.Module):
    def __init__(self, nb_layers, in_planes, out_planes, block, stride, bn_branch, dropRate=0.0):
        super(NetworkBlock_RBN, self).__init__()
        self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, bn_branch, dropRate)
        self.bn_block_num = 2 if block == BasicBlock_RBN else 3

    def _make_layer(self, block, in_planes, out_planes, nb_layers, stride, bn_branch, dropRate):
        layers = []
        for i in range(int(nb_layers)):
            layers.append(block(i == 0 and in_planes or out_planes, out_planes, i == 0 and stride or 1, bn_branch, dropRate))
        return nn.ModuleList(layers)

    def forward(self, x):
        out,bn_r_list = x
        bn_order = 0
        for op in self.layer:
            sub_bn_r_list = bn_r_list[bn_order : bn_order+self.bn_block_num]
            bn_order += self.bn_block_num
            out = op((out,sub_bn_r_list))

        return out


class WideResNet_RBN(nn.Module):
    def __init__(self, depth=34, num_classes=10, widen_factor=10, dropRate=0.0, normalize=None, bn_branch=7, bn_branch_length=30):
        super(WideResNet_RBN, self).__init__()
        nChannels = [16, 16 * widen_factor, 32 * widen_factor, 64 * widen_factor]
        assert ((depth - 4) % 6 == 0)
        n = (depth - 4) / 6
        self.n = int(n)
        block = BasicBlock_RBN
        self.bn_branch = bn_branch
        # 1st conv before any network block
        self.conv1 = nn.Conv2d(3, nChannels[0], kernel_size=3, stride=1,
                               padding=1, bias=False)
        # 1st block
        self.block1 = NetworkBlock_RBN(n, nChannels[0], nChannels[1], block, 1, bn_branch, dropRate)
        # 2nd block
        self.block2 = NetworkBlock_RBN(n, nChannels[1], nChannels[2], block, 2, bn_branch, dropRate)
        # 3rd block
        self.block3 = NetworkBlock_RBN(n, nChannels[2], nChannels[3], block, 2, bn_branch, dropRate)
        # global average pooling and classifier
        self.bn1 = nn.BatchNorm2d(nChannels[3])
        self.relu = nn.ReLU(inplace=True)
        self.fc = nn.Linear(nChannels[3], num_classes)
        self.nChannels = nChannels[3]
        self.branch_list = [0]*bn_branch_length
        self.bn_block_num = 2 if block == BasicBlock_RBN else 3
        self.normalize = normalize

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.Linear):
                m.bias.data.zero_()

    def forward(self, x):
        bn_order = 0
        if self.normalize is not None:
            x = self.normalize(x)

        out = self.conv1(x)
        # print(bn_order, self.bn_block_num, self.n)
        # print(self.branch_list[bn_order : bn_order + self.bn_block_num * self.n])
        # exit()
        out = self.block1((out,self.branch_list[bn_order : bn_order + self.bn_block_num * self.n]))
        bn_order += self.bn_block_num*self.n
        out = self.block2((out,self.branch_list[bn_order : bn_order+self.bn_block_num*self.n]))
        bn_order += self.bn_block_num*self.n
        out = self.block3((out,self.branch_list[bn_order : bn_order+self.bn_block_num*self.n]))
        bn_order += self.bn_block_num*self.n

        out = self.relu(self.bn1(out))
        out = F.avg_pool2d(out, 8)
        out = out.view(-1, self.nChannels)
        return self.fc(out)


    def set_precision(self, num_bits=None, num_grad_bits=None):
        pass
    
    def set_random_branch(self,branch):
        if type(branch)==int:
            for i in range(len(self.branch_list)):
                self.branch_list[i] = branch
        if isinstance(branch,list):
            self.branch_list = branch
        return branch


def WideResNet32_RBN(num_classes=10,bn_branch=7, normalize=None):
    return WideResNet_RBN(num_classes=num_classes, bn_branch=bn_branch, normalize=normalize, bn_branch_length=30, dropRate=0.8)